import { Component, OnInit } from '@angular/core';

import { NameLabel } from '@core/base';
import { Config, CustomService, Task, TaskQuery } from '@core/job/custom';
import { NzMessageService } from 'ng-zorro-antd/message';

import { CustomConfigFormService } from './custom-config-form.service';

@Component({
  selector: 'app-custom-task-list',
  templateUrl: './custom-task-list.component.html',
  styleUrls: ['./custom-task-list.component.less'],
  providers: [CustomConfigFormService]
})
export class CustomTaskListComponent implements OnInit {
  query: TaskQuery = new TaskQuery();
  tasks: Task[] = [];
  taskStates: NameLabel[] = [];

  isLoading = false;

  constructor(
    private customSrc: CustomService,
    private messageSrc: NzMessageService,
    private customConfigFormSrc: CustomConfigFormService
  ) {}

  ngOnInit(): void {
    this.loadEnum();
    this.loadTasks();
  }

  loadEnum(): void {
    this.customSrc.getEnum().subscribe(data => (this.taskStates = data));
  }

  loadTasks(): void {
    this.isLoading = true;
    this.customSrc.getTasks(this.query).subscribe(data => {
      this.tasks = data;
      this.isLoading = false;
    });
  }

  add(): void {
    const modal = this.customConfigFormSrc.open('新任务配置', { config: new Config() });

    modal.afterClose.subscribe(formValue => {
      if (formValue) {
        this.customSrc.createConfig(formValue).subscribe(() => {
          this.loadTasks();
          this.messageSrc.success('新任务配置成功');
        });
      }
    });
  }
}
